package com.webex.ta.hydra.core.control;

import com.webex.ta.hydra.core.Command;
import com.webex.ta.hydra.core.ParamDescriptor;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

/**
 * Created by IntelliJ IDEA.
 * User: vegaz
 * Date: 2010-8-30
 * Time: 10:17:39
 * To change this template use File | Settings | File Templates.
 */
public class IfController extends GenericController {
    static ParamDescriptor[] desc = new ParamDescriptor[1];
    static {
        desc[0] = new ParamDescriptor("condition (in javascript)");
    }

    public ParamDescriptor[] getParamDescriptors(Command cmd) {
        return desc;
    }

    public Command next() {
        // We should only evalute the condition if it is the first
        // time ( first "iteration" ) we are called.
        // For subsequent calls, we are inside the IfControllerGroup,
        // so then we just pass the control to the next item inside the if control
        boolean result = true;
//        if(isEvaluateAll() || isFirst()) {
        if(isFirst()) {
            result = evaluateCondition(this.params[0].getStringValue());
        }

		if (result) {
			return super.next();
		}
		try {
			return nextIsNull();
		} catch (NextIsNullException e1) {
			return null;
		}
	}

    static boolean evaluateCondition(String cond) {

		String resultStr = "";
		boolean result = false;

		// now evaluate the condition using JavaScript
		Context cx = Context.enter();
		try {
			Scriptable scope = cx.initStandardObjects(null);
			Object cxResultObject = cx.evaluateString(scope, cond
			/** * conditionString ** */
			, "<cmd>", 1, null);
			resultStr = Context.toString(cxResultObject);

			if (resultStr.equals("false")) { //$NON-NLS-1$
				result = false;
			} else if (resultStr.equals("true")) { //$NON-NLS-1$
				result = true;
			} else {
				throw new Exception(" BAD CONDITION :: " + cond + " :: expected true or false");
			}
		} catch (Exception e) {

		} finally {
			Context.exit();
		}

		return result;
	}
}
